import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'edit_state.dart';

/// 编辑页面逻辑控制器 - Edit Page Logic Controller
///
/// 处理编辑页面的所有业务逻辑，包括内容编辑、格式化、变量管理等
/// Handles all business logic for edit page including content editing, formatting, variable management
class EditLogic extends GetxController {
  final EditState state = EditState();

  @override
  void onInit() {
    super.onInit();
    _initializeData();
  }

  @override
  void onClose() {
    state.titleController.dispose();
    state.descriptionController.dispose();
    state.contentController.dispose();
    super.onClose();
  }

  /// 初始化数据 - Initialize Data
  void _initializeData() {
    // 获取传递的参数 - Get passed parameters
    final arguments = Get.arguments as Map<String, dynamic>?;

    if (arguments != null) {
      final promptId = arguments['promptId'] as String?;
      if (promptId != null) {
        _loadPrompt(promptId);
      }
    }

    // 监听内容变化 - Listen to content changes
    state.contentController.addListener(_onContentChanged);
    state.titleController.addListener(_onTitleChanged);
    state.descriptionController.addListener(_onDescriptionChanged);
  }

  /// 加载 Prompt 数据 - Load Prompt Data
  void _loadPrompt(String promptId) {
    // TODO: 从文件系统加载 Prompt 数据
    // Load Prompt data from file system
    state.isNewPrompt.value = false;
    state.promptId.value = promptId;
  }

  /// 内容变化处理 - Handle Content Changes
  void _onContentChanged() {
    state.hasUnsavedChanges.value = true;
    _updateWordCount();
    _extractVariables();
    update(['word_count', 'preview_content', 'variables_list']);
  }

  /// 标题变化处理 - Handle Title Changes
  void _onTitleChanged() {
    state.hasUnsavedChanges.value = true;
  }

  /// 描述变化处理 - Handle Description Changes
  void _onDescriptionChanged() {
    state.hasUnsavedChanges.value = true;
  }

  /// 更新字数统计 - Update Word Count
  void _updateWordCount() {
    final text = state.contentController.text;
    state.wordCount.value = text.length;
  }

  /// 提取模板变量 - Extract Template Variables
  void _extractVariables() {
    final text = state.contentController.text;
    final regex = RegExp(r'\{\{(\w+)\}\}');
    final matches = regex.allMatches(text);

    final extractedVars = <String>{};
    for (final match in matches) {
      final varName = match.group(1);
      if (varName != null) {
        extractedVars.add(varName);
      }
    }

    // 添加新发现的变量 - Add newly discovered variables
    for (final varName in extractedVars) {
      if (!state.variables.any((v) => v.name == varName)) {
        state.variables.add(TemplateVariable(
          name: varName,
          description: '',
          defaultValue: '',
        ));
      }
    }

    // 移除不再使用的变量 - Remove unused variables
    state.variables
        .removeWhere((variable) => !extractedVars.contains(variable.name));
  }

  /// 切换预览模式 - Toggle Preview Mode
  void togglePreviewMode() {
    state.isPreviewMode.value = !state.isPreviewMode.value;
    update(['preview_mode']);
  }

  /// 内容变化回调 - Content Change Callback
  void onContentChanged(String value) {
    // 已在 _onContentChanged 中处理
    // Already handled in _onContentChanged
  }

  /// 标题变化回调 - Title Change Callback
  void onTitleChanged(String? value) {
    // 已在 _onTitleChanged 中处理
    // Already handled in _onTitleChanged
  }

  /// 描述变化回调 - Description Change Callback
  void onDescriptionChanged(String? value) {
    // 已在 _onDescriptionChanged 中处理
    // Already handled in _onDescriptionChanged
  }

  /// 分类变化回调 - Category Change Callback
  void onCategoryChanged(String? value) {
    if (value != null) {
      state.selectedCategory.value = value;
      state.hasUnsavedChanges.value = true;
    }
  }

  /// 格式变化回调 - Format Change Callback
  void onFormatChanged(String? value) {
    if (value != null) {
      state.selectedFormat.value = value;
      state.hasUnsavedChanges.value = true;
    }
  }

  /// 插入格式化文本 - Insert Formatted Text
  void insertFormat(String prefix, String suffix) {
    final controller = state.contentController;
    final selection = controller.selection;

    if (selection.isValid) {
      final text = controller.text;
      final selectedText = text.substring(selection.start, selection.end);
      final newText = '$prefix$selectedText$suffix';

      controller.text =
          text.replaceRange(selection.start, selection.end, newText);

      // 设置新的光标位置 - Set new cursor position
      final newCursorPos =
          selection.start + prefix.length + selectedText.length + suffix.length;
      controller.selection = TextSelection.collapsed(offset: newCursorPos);
    }
  }

  /// 插入链接 - Insert Link
  void insertLink() {
    _showInsertDialog(
      title: '插入链接',
      fields: ['链接文本', '链接地址'],
      onConfirm: (values) {
        final linkText = values[0];
        final linkUrl = values[1];
        _insertTextAtCursor('[$linkText]($linkUrl)');
      },
    );
  }

  /// 插入图片 - Insert Image
  void insertImage() {
    _showInsertDialog(
      title: '插入图片',
      fields: ['图片描述', '图片地址'],
      onConfirm: (values) {
        final altText = values[0];
        final imageUrl = values[1];
        _insertTextAtCursor('![$altText]($imageUrl)');
      },
    );
  }

  /// 插入表格 - Insert Table
  void insertTable() {
    const tableTemplate = '''
| 列1 | 列2 | 列3 |
|-----|-----|-----|
| 行1 | 数据 | 数据 |
| 行2 | 数据 | 数据 |
''';
    _insertTextAtCursor(tableTemplate);
  }

  /// 插入变量 - Insert Variable
  void insertVariable() {
    if (state.variables.isEmpty) {
      Get.snackbar('提示', '请先添加模板变量');
      return;
    }

    Get.bottomSheet(
      Container(
        padding: const EdgeInsets.all(16),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '选择变量',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            ),
            const SizedBox(height: 16),
            ...state.variables.map((variable) => ListTile(
                  title: Text('{{${variable.name}}}'),
                  subtitle: variable.description.isNotEmpty
                      ? Text(variable.description)
                      : null,
                  onTap: () {
                    _insertTextAtCursor('{{${variable.name}}}');
                    Get.back();
                  },
                )),
          ],
        ),
      ),
    );
  }

  /// 在光标位置插入文本 - Insert Text at Cursor
  void _insertTextAtCursor(String text) {
    final controller = state.contentController;
    final selection = controller.selection;

    if (selection.isValid) {
      final currentText = controller.text;
      final newText =
          currentText.replaceRange(selection.start, selection.end, text);

      controller.text = newText;
      controller.selection = TextSelection.collapsed(
        offset: selection.start + text.length,
      );
    }
  }

  /// 显示插入对话框 - Show Insert Dialog
  void _showInsertDialog({
    required String title,
    required List<String> fields,
    required Function(List<String>) onConfirm,
  }) {
    final controllers = fields.map((field) => TextEditingController()).toList();

    Get.dialog(
      AlertDialog(
        title: Text(title),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: fields.asMap().entries.map((entry) {
            final index = entry.key;
            final field = entry.value;
            return Padding(
              padding: const EdgeInsets.only(bottom: 16),
              child: TextField(
                controller: controllers[index],
                decoration: InputDecoration(
                  labelText: field,
                  border: const OutlineInputBorder(),
                ),
              ),
            );
          }).toList(),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final values = controllers.map((c) => c.text).toList();
              onConfirm(values);
              Get.back();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 处理菜单操作 - Handle Menu Actions
  void handleMenuAction(String action) {
    switch (action) {
      case 'export':
        _exportPrompt();
        break;
      case 'duplicate':
        _duplicatePrompt();
        break;
      case 'delete':
        _deletePrompt();
        break;
    }
  }

  /// 导出 Prompt - Export Prompt
  void _exportPrompt() {
    // TODO: 实现导出功能
    // Implement export functionality
    Get.snackbar('提示', '导出功能开发中...');
  }

  /// 复制 Prompt - Duplicate Prompt
  void _duplicatePrompt() {
    // TODO: 实现复制功能
    // Implement duplicate functionality
    Get.snackbar('提示', '复制功能开发中...');
  }

  /// 删除 Prompt - Delete Prompt
  void _deletePrompt() {
    Get.dialog(
      AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个 Prompt 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // TODO: 实现删除逻辑
              // Implement delete logic
              Get.back();
              Get.back();
              Get.snackbar('成功', 'Prompt 已删除');
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 移除标签 - Remove Tag
  void removeTag(String tag) {
    state.selectedTags.remove(tag);
    state.hasUnsavedChanges.value = true;
  }

  /// 显示添加标签对话框 - Show Add Tag Dialog
  void showAddTagDialog() {
    final controller = TextEditingController();

    Get.dialog(
      AlertDialog(
        title: const Text('添加标签'),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(
            labelText: '标签名称',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final tag = controller.text.trim();
              if (tag.isNotEmpty && !state.selectedTags.contains(tag)) {
                state.selectedTags.add(tag);
                state.hasUnsavedChanges.value = true;
              }
              Get.back();
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }

  /// 添加变量 - Add Variable
  void addVariable() {
    final nameController = TextEditingController();
    final descController = TextEditingController();
    final defaultController = TextEditingController();

    Get.dialog(
      AlertDialog(
        title: const Text('添加模板变量'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: nameController,
              decoration: const InputDecoration(
                labelText: '变量名称',
                hintText: '例如: userName',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: descController,
              decoration: const InputDecoration(
                labelText: '变量描述',
                hintText: '描述这个变量的用途',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: defaultController,
              decoration: const InputDecoration(
                labelText: '默认值（可选）',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final name = nameController.text.trim();
              if (name.isNotEmpty) {
                state.variables.add(TemplateVariable(
                  name: name,
                  description: descController.text.trim(),
                  defaultValue: defaultController.text.trim(),
                ));
                state.hasUnsavedChanges.value = true;
              }
              Get.back();
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }

  /// 移除变量 - Remove Variable
  void removeVariable(int index) {
    if (index >= 0 && index < state.variables.length) {
      state.variables.removeAt(index);
      state.hasUnsavedChanges.value = true;
    }
  }

  /// 查看版本历史 - View Version History
  void viewVersionHistory() {
    Get.toNamed('/version', arguments: {'promptId': state.promptId});
  }

  /// 对比版本 - Compare Versions
  void compareVersions() {
    // TODO: 实现版本对比功能
    // Implement version comparison functionality
    Get.snackbar('提示', '版本对比功能开发中...');
  }

  /// 显示属性面板 - Show Properties Panel (Mobile)
  void showPropertiesPanel() {
    Get.bottomSheet(
      Container(
        height: Get.height * 0.8,
        padding: const EdgeInsets.all(16),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Text(
                  '属性设置',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                ),
                const Spacer(),
                IconButton(
                  onPressed: () => Get.back(),
                  icon: const Icon(Icons.close),
                ),
              ],
            ),
            const Divider(),
            // TODO: 添加属性面板内容
            // Add properties panel content
          ],
        ),
      ),
    );
  }

  /// 显示变量面板 - Show Variables Panel (Mobile)
  void showVariablesPanel() {
    Get.bottomSheet(
      Container(
        height: Get.height * 0.8,
        padding: const EdgeInsets.all(16),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Text(
                  '模板变量',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                ),
                const Spacer(),
                IconButton(
                  onPressed: () => Get.back(),
                  icon: const Icon(Icons.close),
                ),
              ],
            ),
            const Divider(),
            // TODO: 添加变量面板内容
            // Add variables panel content
          ],
        ),
      ),
    );
  }

  /// 保存 Prompt - Save Prompt
  void savePrompt() {
    if (state.titleController.text.trim().isEmpty) {
      Get.snackbar('错误', '请输入 Prompt 标题');
      return;
    }

    if (state.contentController.text.trim().isEmpty) {
      Get.snackbar('错误', '请输入 Prompt 内容');
      return;
    }

    // TODO: 实现保存逻辑到文件系统
    // Implement save logic to file system

    state.hasUnsavedChanges.value = false;
    state.currentVersion.value = state.currentVersion.value + 1;

    Get.snackbar('成功', 'Prompt 已保存');
  }
}
